/* eslint quotes: 0 */
import React, {PureComponent} from "react";
import {
    Dimensions,
    StyleSheet,
    View,
    Text,
    Button,
    StatusBar,
    TouchableOpacity,
    Image,
    TextInput,
    FlatList,
    SafeAreaView,
    ToastAndroid,
    Keyboard,
    DeviceEventEmitter
} from "react-native";
import Tips from 'react-native-root-tips'
import {fetchGetRequest} from "../../api/NetworkTool";
import api from "../../api/api";
import method from "../../api/method";
const DEVICE_WIDTH = Dimensions.get(`window`).width;
type State = {
    search_text: string
}
const Realm = require('realm');
let realm;
const CarSchema = {
    name: 'Car',
    primaryKey: 'id',
    properties: {
        id: 'int',
        car_name: 'string',
    }
};

export default class SearchScene extends PureComponent<State> {

    static navigationOptions = ({navigation}: any) => ({
        header: null,
    });

    constructor(props) {
        super(props);

        //初始化Realm
        realm = new Realm({schema: [CarSchema]});

        this.state = {

            content: (Realm.defaultPath),
            topic: [],
            search_text: '',
            search_history: [],
            search_text: '',

        };
    }


    render() {

        return (
            <SafeAreaView style={ styles.container }>
                <View style={ styles.header}>
                    <TouchableOpacity onPress={()=>{this.goBack()}}>
                        <Image style={styles.imageBack} source={require('../../../res/img/gobal_back.png')}/>
                    </TouchableOpacity>

                    <TextInput
                        style={styles.inputStyle}
                        placeholder="搜索你想学的科目、老师试试"// = android　EditText hint
                        placeholderTextColor="#999999"// = hint color
                        underlineColorAndroid='transparent'// 下划线透明
                        clearButtonMode="while-editing"
                        //   onFocus={() =>console.log('onFocus')} //选中文本框
                        //   onBlur={() =>console.log('onBlur')}//离开文本框
                        //  onChange={() =>console.log('onChange')}//文本框内容变化
                        onChangeText={(text) =>this.setState({search_text: text})}//文本框内容变化，变化的内容
                        //  onEndEditing={() =>console.log('onEndEditing')}//文本框编译结束
                        //   onSubmitEditing={() =>console.log('onSubmitEditing')}//按下回车键
                        // autoCorrect={false}
                        //editable={false}
                        //keyboardType='url' web-search
                    />
                    <TouchableOpacity onPress={()=>{this.searchInfo()}}
                                      style={styles.btnSearch}>
                        <Text style={{color:'white',fontSize:12,}}>搜索</Text>
                    </TouchableOpacity>
                </View>
                <FlatList
                    data={this.state.search_history}
                    keyExtractor={(item, index) => index}
                    renderItem={this.renderListItem}
                    ListHeaderComponent={this.renderHistoryHeader}/>

            </SafeAreaView>
        );
    }

    renderHistoryHeader = () => {
        return (
            <View style={{backgroundColor:'#f9f9f9'}}>
                <View style={{height:0.5,width:DEVICE_WIDTH ,backgroundColor:'#DFDFDF',marginBottom:12}}/>
                <View style={{marginLeft:12,backgroundColor:'#f9f9f9'}}>
                    <Text style={styles.searchLeft}>热门搜索</Text>
                </View>

                <FlatList
                    data={this.state.topic}
                    keyExtractor={(item, index) => index}
                    renderItem={this.renderTagItem}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                />

                <View style={{height:0.5,width:DEVICE_WIDTH ,backgroundColor:'#DFDFDF',marginTop:12}}/>

                {this.checkHeaderVisible()}


            </View>
        )


    }

    checkHeaderVisible() {
        if (this.state.search_history.length > 0) {
            return <View
                style={styles.deleteHistory}>
                <Text style={styles.searchLeft2}>历史搜索</Text>
                <View style={{flexDirection:'row',}}>
                    <Image style={{marginTop:19}}
                           source={require('../../../res/img/search/gabagge.png')}/>
                    <TouchableOpacity onPress={()=>{
                            realm.write(()=> {
                            let cars = realm.objects('Car');
                            realm.delete(cars);
                            this.reloadHistory()
                        });
                        }}>
                        <Text style={styles.searchRight}>清空历史记录</Text>
                    </TouchableOpacity>
                </View>
            </View>

        } else {
            return <View>
            </View>
        }
    }

    reloadHistory() {
        let cars = realm.objects('Car');
        let temp = []

        for (let i = 0; i < cars.length; i++) {
            let car = cars[i];
            temp.push(car.car_name)
        }

        this.setState({
            search_history: Array.from(new Set(temp.reverse()))//去重+反转
        })
    }

    componentDidMount() {

        this.setState({
            topic: this.props.navigation.state.params.hotwords
        })

        this.reloadHistory()
        DeviceEventEmitter.addListener('async', (a) => {
            realm.write(() => {
                realm.create('Car', {id: Date.parse(new Date()), car_name: a}, true);
            })
            this.reloadHistory()
        });
    }

    renderTagItem = ({item}) => {
        return (
            <TouchableOpacity onPress={()=>{this.searchTagInfo(item)}}
                              style={styles.btnTag}>
                <Text style={{color:'#686868',fontSize:12,}}>{item}</Text>
            </TouchableOpacity>
        )
    }

    renderListItem = ({item}) => {
        return (
            <TouchableOpacity onPress={()=>{this.searchTagInfo(item)}}>
                <View style={{alignItems:'center',justifyContent:'center',marginTop:8,marginBottom:8,paddingLeft:24}}>
                    <Text
                        style={{width:DEVICE_WIDTH,color:'#686868',fontSize:12,marginLeft:12,marginRight:12,}}>{item}</Text>
                </View>
                <View style={{height:0.5,marginLeft:12,width:DEVICE_WIDTH - 24 ,backgroundColor:'#DFDFDF'}}/>
            </TouchableOpacity>
        )
    }

    goBack() {
        this.props.navigation.goBack()
    }


    /**
     * 点击搜索按钮搜索
     */
    searchInfo() {

        if (this.state.search_text === '') {
            Tips.showWarn('请输入搜索关键字！', {mask: true})
            return
        }

        if (this.state.search_text.replace(/(^\s*)/g, "") === '') {
            Tips.showWarn('请输入有效关键字！', {mask: true})
            return
        }

        this.requestNetData(this.state.search_text)

        Keyboard.dismiss()

    }

    requestNetData(keyword) {
        fetchGetRequest(api.searchInfo, method.get, {keyword: keyword})
            .then(res => {
                console.log(res)

                if (res.teachers.length == 0 && res.common_courses.length == 0 && res.courses.length == 0) {
                    Tips.showWarn('没有搜索到任何结果/(ㄒoㄒ)/~~', {mask: true})
                    DeviceEventEmitter.emit('async', keyword);
                    return
                }

                this.props.navigation.navigate('searchResultScene',
                    {
                        'keyword': keyword,
                    })

            })
            .catch(err => {

            })
    }

    /**
     * 点击热门标签或历史记录搜索
     * @param title
     */
    searchTagInfo(title) {
        // this.setState({search_text: title})
        // this.props.navigation.navigate('searchResultScene', {'keyword': title})
        this.requestNetData(title)

    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9'
    },
    header: {
        flexDirection: `row`,
        justifyContent: 'space-between',
        alignItems: 'center',
        width: DEVICE_WIDTH,
        height: 56,
        backgroundColor: '#f9f9f9'
    },
    imageBack: {
        marginLeft: 12
    },
    btnSearch: {
        marginLeft: 14,
        marginRight: 13,
        borderRadius: 30,
        backgroundColor: '#DB3843',
        height: 25,
        width: 56,
        justifyContent: 'center',
        alignItems: 'center'
    },
    btnTag: {
        borderRadius: 30,
        backgroundColor: '#F0F2F5',
        height: 20,
        width: 64,
        justifyContent: 'center',
        alignItems: 'center',
        marginLeft: 12,
        marginRight: 12
    },
    inputStyle: {
        height: 25,
        flex: 1,
        borderColor: 'white',
        borderWidth: 0.1,
        fontSize: 12,
        marginLeft: 19,
        borderRadius: 20,
        paddingLeft: 21,
        paddingRight: 21,
        paddingBottom: 5,
        paddingTop: 5,
        backgroundColor: '#ebebeb'
    },
    searchLeft: {
        fontSize: 14,
        color: 'black',
        width: DEVICE_WIDTH,
        marginBottom: 15
    },
    searchLeft2: {
        fontSize: 14,
        color: 'black',
        marginTop: 15,
    },
    searchRight: {
        fontSize: 12,
        color: '#999999',
        marginBottom: 15,
        marginRight: 24,
        marginTop: 17,
        marginLeft: 5
    },
    deleteHistory: {
        width: DEVICE_WIDTH,
        justifyContent: 'space-between',
        flexDirection: 'row',
        marginLeft: 12,
        flex: 1,
    }
});
